package com.example.taobaounion.view.fragment;

import android.graphics.Rect;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;
import com.example.taobaounion.manager.PresenterManager;
import com.example.taobaounion.model.domain.SearchRecommend;
import com.example.taobaounion.model.domain.SearchResult;
import com.example.taobaounion.presenter.impl.SearchPresenter;
import com.example.taobaounion.utils.KeyboardUtil;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.SizeUtils;
import com.example.taobaounion.utils.TicketUtil;
import com.example.taobaounion.utils.ToastUtils;
import com.example.taobaounion.view.adapter.HomePageContentAdapter;
import com.example.taobaounion.view.callback.ISearchViewCallback;
import com.example.taobaounion.view_component.TextFlowLayout;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

public class SearchFragment extends BaseFragment {

    @BindView(R.id.search_history_view)
    public TextFlowLayout mHistoryTextFlow;

    @BindView(R.id.search_recommend_view)
    public TextFlowLayout mRecommendTextFlow;

    @BindView(R.id.search_recommend_container)
    public LinearLayout mRecommendContainer;

    @BindView(R.id.search_history_container)
    public LinearLayout mHistoryContainer;

    @BindView(R.id.search_history_delete)
    public ImageView mDeleteImg;

    @BindView(R.id.search_result_list)
    public RecyclerView mSearchResultList;

    @BindView(R.id.search_result_container)
    public TwinklingRefreshLayout mRefreshLayout;

    @BindView(R.id.search_remove_btn)
    public ImageView mSearchRemoveBtn;

    @BindView(R.id.search_btn)
    public TextView mSearchBtn;

    @BindView(R.id.search_input_box)
    public EditText mSearchInputBox;

    public static final String TAG = "SearchFragment";
    private ISearchViewCallback mISearchViewCallback;
    private SearchPresenter mSearchPresenter;
    private HomePageContentAdapter mSearchResultAdapter;

    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_search_layout, container, false);
    }

    @Override
    protected void initView(View view) {

        mRefreshLayout.setEnableRefresh(false);

        // set search result layout way
        mSearchResultList.setLayoutManager(new LinearLayoutManager(getContext()));

        // 搜索结果间添加间隔
        mSearchResultList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.top = SizeUtils.dip2px(Objects.requireNonNull(getContext()), 1.5f);
                outRect.bottom = SizeUtils.dip2px(Objects.requireNonNull(getContext()), 1.5f);
            }
        });
        // show success view
        setUpState(STATE.SUCCESS);
    }

    @Override
    protected void initPresenter() {
        mSearchPresenter = PresenterManager.getInstance().getSearchPresenter();

        mISearchViewCallback = new ISearchViewCallback() {
            @Override
            public void onNetworkError() {
                setUpState(STATE.ERROR);
            }

            @Override
            public void onLoading() {
                setUpState(STATE.LOADING);
            }

            @Override
            public void onEmpty() {
                setUpState(STATE.EMPTY);
            }

            @Override
            public void onHistoriesLoaded(List<String> histories) {
                LogUtils.d(TAG, "history size-->" + histories);

                if (histories == null || histories.size() == 0) {
                    mHistoryContainer.setVisibility(View.GONE);
                } else {
                    mHistoryContainer.setVisibility(View.VISIBLE);
                    mHistoryTextFlow.setTextList(histories);
                }
            }

            @Override
            public void onHistoriesDeleted() {
                if (mSearchPresenter != null) {
                    mSearchPresenter.getHistories();
                }
            }

            @Override
            public void onSearchSuccess(List<SearchResult.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> result) {
                LogUtils.d(TAG, "result size-->" + result.size());

                // 隐藏历史记录和推荐
                mRecommendContainer.setVisibility(View.GONE);
                mHistoryContainer.setVisibility(View.GONE);
                // 显示搜索界面
                mRefreshLayout.setVisibility(View.VISIBLE);
                // 设置数据

                mSearchResultAdapter.setDate(result);
            }

            @Override
            public void onMoreLoaded(List<SearchResult.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> result) {
                mSearchResultAdapter.addData(result);
                ToastUtils.showToast("添加" + result.size() + "条内容");
                mRefreshLayout.finishLoadmore();
            }

            @Override
            public void onMoreLoaderError() {
                ToastUtils.showToast("添加内容失败,稍后重试");
                mRefreshLayout.finishLoadmore();
            }

            @Override
            public void onMoreLoadedEmpty() {
                ToastUtils.showToast("添加没有更多内容");
                mRefreshLayout.finishLoadmore();
            }

            @Override
            public void onRecommendWordsLoaded(List<SearchRecommend.DataBean> pRecommendWords) {
                LogUtils.d(TAG, "recommend size-->" + pRecommendWords.size());

                List<String> lRecommendKeyWords = new ArrayList<>();
                for (SearchRecommend.DataBean lRecommendWord : pRecommendWords) {
                    lRecommendKeyWords.add(lRecommendWord.getKeyword());
                }

                if (lRecommendKeyWords.size() == 0) {
                    mRecommendContainer.setVisibility(View.GONE);
                } else {
                    mRecommendContainer.setVisibility(View.VISIBLE);
                    mRecommendTextFlow.setTextList(lRecommendKeyWords);
                }

            }
        };
        mSearchPresenter.registerViewCallback(mISearchViewCallback);
    }

    @Override
    protected void initListener() {

        mSearchBtn.setOnClickListener(v -> {
            if (((TextView) v).getText().toString().equals(getResources().getString(R.string.text_search))) {
                if (mSearchPresenter != null) {

                    doSearch(mSearchInputBox.getText().toString().trim());

                    KeyboardUtil.hide(Objects.requireNonNull(getContext()), v);
                }
            } else {
                KeyboardUtil.hide(Objects.requireNonNull(getContext()), v);
            }
        });

        mSearchInputBox.setOnEditorActionListener((v, actionId, event) -> {

                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        if (mSearchPresenter != null) {
                            mSearchPresenter.doSearch(v.getText().toString().trim());
                        }
                    }
                    return false;
                }

        );

        mSearchInputBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                boolean lHaveText = s.toString().trim().length() > 0;
                boolean lHaveInput = s.toString().length() > 0;

                mSearchRemoveBtn.setVisibility(lHaveInput ? View.VISIBLE : View.GONE);

                mSearchBtn.setText(lHaveText ? R.string.text_search : R.string.text_undo);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        mSearchRemoveBtn.setOnClickListener(v -> {
            mSearchInputBox.setText("");

            switch2HistoryPage();
        });


        mSearchResultAdapter.setOnListenerItemClickListener(dataBean -> TicketUtil.toTicketPage(

                getContext(), dataBean));

        mDeleteImg.setOnClickListener(v ->

        {
            // 清空历史
            mSearchPresenter.delHistories();
        });


        // 搜索事件
        mHistoryTextFlow.setonFlowTextItemClickListener(this::doSearch);

        mRecommendTextFlow.setonFlowTextItemClickListener(this::doSearch);


        // 上拉刷新的事件
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {

                if (mSearchPresenter != null) {
                    mSearchPresenter.loaderMore();
                }
            }
        });
    }

    private void doSearch(String text) {
        mSearchResultList.scrollToPosition(0);
        mSearchPresenter.doSearch(text);
        mSearchInputBox.setText(text);
        mSearchInputBox.setFocusable(true);
        mSearchInputBox.setSelection(text.length());
    }

    /**
     * 切换到历史推荐界面
     */
    private void switch2HistoryPage() {
        if (mHistoryTextFlow.getContentSize() != 0) {
            mHistoryContainer.setVisibility(View.VISIBLE);
        } else {
            mHistoryContainer.setVisibility(View.GONE);
        }

        if (mRecommendTextFlow.getContentSize() != 0) {
            mRecommendContainer.setVisibility(View.VISIBLE);
        } else {
            mRecommendContainer.setVisibility(View.GONE);
        }

        // 内容要隐藏
        mRefreshLayout.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        mSearchPresenter.getRecommendWords();
        mSearchPresenter.getHistories();
    }

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_search;
    }

    @Override
    protected void release() {
        if (mSearchPresenter != null) {
            mSearchPresenter.unRegisterViewCallback(mISearchViewCallback);
        }
    }

    @Override
    protected void initAdapter() {
        mSearchResultAdapter = new HomePageContentAdapter();

        mSearchResultList.setAdapter(mSearchResultAdapter);
    }


    @Override
    protected void onRetryClick() {
        if (mSearchPresenter != null) {
            mSearchPresenter.research();
        }
    }
}
